import {messages} from "share/common";
import React from 'react';
import {connect} from 'react-redux'
import {Button, message, Modal, Steps, DatePicker} from 'antd'
import IndirectUpload from './indirect-upload';
import 'styles/financial-management/check-center/check-center-impoter.scss'
import DdAccountPeriodService
  from "./dd-account-period.service";
import FileSaver from "file-saver";
import moment from "moment";

const {MonthPicker} = DatePicker;
const {Step} = Steps

//数据导入组件
class DdAccountPeriodImporter extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isUpload: false,
      visible: false,
      isFinish: false,// 上传是否完成
      fileList: [],
      accountPeriod: moment(new Date()).format("YYYY-MM"),
      uploading: false,
      stepIndex: 0,
      result: {},
      transactionID: null,
      errorColumns: [],
      errorData: [],
      descTextOfDownload: [`1.${messages('financial-management.key90'/*点击上方按钮*/)}`, `2.${messages('financial-management.key91'/*严格按照导入模板整理数据，检查必输事项是否缺少数据*/)}`, `3.${messages('financial-management.key92'/*保存文件*/)}`],
      descTextOfUpload: [
        `1.${messages('financial-management.key1258'/*选择账期*/)}`,
        `2.${messages('financial-management.key94'/*点击【选择文件】按钮*/)}`,
        `3.${messages('financial-management.key95'/*选择你刚更新过的Excel文件，并点击确定*/)}`, `
        4.${messages('financial-management.key96'/*点击【导入】按钮*/)}`],
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({visible: nextProps.visible})
  }

  componentWillMount() {
  }

  handleOk = () => {
  };

  finishUpload = (res) => {
    const fileName = this.props.fileName;
    this.setState({
      isFinish: true, isUpload: false
    }, () => {
      let b = new Blob([res.data], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      let name =
        `${fileName}-导入结果-` +
        `${new Date().format("yyyyMMddhhmmss")}`;
      FileSaver.saveAs(b, `${name}.xlsx`);
      this.props.onOk()
    });
  }

  setFileList = (fileList) => {
    this.setState({fileList: fileList});
  }

  onCancel = () => {
    this.setState({visible: false, uploading: false, isFinish: false});
  };

  //下载导入模板
  downloadTemplate = () => {
    const fileName = this.props.fileName;
    let hide = message.loading(messages('financial-management.key82'/*正在生成文件..*/));
    DdAccountPeriodService.exportTemplate().then((res) => {
      let b = new Blob([res.data], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      let name =
        `${fileName}` +
        `${new Date().format("yyyyMMddhhmmss")}`;
      FileSaver.saveAs(b, `${name}.xlsx`);
      hide();
    }).catch(() => {
      message.error(messages('financial-management.key83'/*下载失败，请重试*/));
      hide();
    })
  };

//只能上传一个文件
  handleChange = (info) => {
    let fileList = info.fileList;
    fileList = fileList.slice(-1);
    this.setState({fileList})
  };

  setModalFooter = () => {
    const {isFinish, stepIndex} = this.state;
    return (<div>
      <Button onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>
      {stepIndex > 0 && <Button type='primary'
                                onClick={() => {this.setState({stepIndex: stepIndex - 1})}}>{messages('financial-management.key1257'/*上一步*/)}</Button>}
      {stepIndex < 1 && <Button type='primary'
                                onClick={() => {this.setState({stepIndex: stepIndex + 1})}}>{messages('financial-management.key1256'/*下一步*/)}</Button>}
    </div>)
  }

  render() {
    const {title, uploadUrl, params} = this.props;
    const {
      visible, uploading, descTextOfDownload, descTextOfUpload, stepIndex, accountPeriod
    } = this.state;

    return (<Modal className="importer"
                   visible={visible}
                   onCancel={this.onCancel}
                   afterClose={this.props.afterClose}
                   title={title}
                   footer={this.setModalFooter()}
                   confirmLoading={uploading}
    >
      <Steps current={stepIndex}>
        <Step title={messages('financial-management.key1255'/*下载导入模板*/)}/>
        <Step title={messages('financial-management.key93'/*上传电子表格*/)}/>
      </Steps>
      <div className="meiya-account-period-import-box-body">
        {stepIndex === 0 && <div>
          <Button type="primary" onClick={this.downloadTemplate}>
            {messages('financial-management.key89'/*下载Excel电子表格*/)}
          </Button>
          <br/>
          {descTextOfDownload.map((item, index) => {
            return (<div style={{margin: '2px 0'}} key={index}>{item}<br/></div>)
          })}
        </div>}
        {stepIndex === 1 &&
          <div>
            {descTextOfUpload.map((item, index) => {
              return (<div style={{margin: '2px 0'}} key={index}>{item}<br/></div>)
            })}
            <br/>
            <div>
              <span>{messages('financial-management.key1258'/*选择账期*/)}：</span>
              <MonthPicker defaultValue={moment(new Date(), 'YYYY-MM')}
                           onChange={(date, dateString) => {this.setState({accountPeriod: dateString})}}/>
              {visible && <IndirectUpload
                returnFileList={this.setFileList}
                uploadUrl={uploadUrl}
                params={{accountPeriod}}
                finishUpload={this.finishUpload}
              />}
            </div>
          </div>
        }
      </div>
    </Modal>);
  }
}

DdAccountPeriodImporter.propTypes = {
  visible: React.PropTypes.bool,        //导入弹框是否可见
  templateUrl: React.PropTypes.string,  //模版下载接口
  uploadUrl: React.PropTypes.string,    //上传接口
  errorUrl: React.PropTypes.string,     //错误信息下载接口，不需要写transactionID变量
  title: React.PropTypes.string,        //标题
  fileName: React.PropTypes.string,     //下载文件名
  onOk: React.PropTypes.func,           //导入成功回调
  afterClose: React.PropTypes.func,     //关闭后的回调
  descDownload: React.PropTypes.array,  //下载模板描述
  descUpload: React.PropTypes.array,    //上传模板描述
  isReplace: React.PropTypes.bool,      //是否替换原来描述
};

DdAccountPeriodImporter.defaultProps = {
  title: '导入', fileName: '导入文件', isReplace: false, params: {}, onOk: () => {}, afterClose: () => {},
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(DdAccountPeriodImporter);
